package com.tib.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tib.dao.UserMapper;
import com.tib.pojo.User;
import com.tib.service.UserService;
import com.tib.utils.JwtUtil;
import com.tib.utils.PageResult;
import com.tib.utils.ResponseResult;
import com.tib.em.StatusConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //获取所有人的信息
    @Override
    public List<User> queryAll() {
        System.out.println(userMapper.queryAll());
        return userMapper.queryAll();
    }

    //通过ID获取用户信息
    @Override
    public User queryUserByID(Integer id) {
        return userMapper.queryUserByID(id);
    }

    //通过账号和密码查找用户
    @Override
    public ResponseResult queryIDAndPassword(User user) {
        User userDetail = userMapper.queryIDAndPassword(user);
        //1、返回结果的map
        HashMap<String,Object> result = new HashMap<>();
        result.put("userDetail",userDetail);

        if(userDetail!=null){
            //2、给予token的负载
            HashMap<String,Object> tokenMap = new HashMap<>();
            tokenMap.put("username",userDetail.getUsername());
            tokenMap.put("userpass",userDetail.getUserpass());
            try {
                //创建token
                result.put("token",JwtUtil.createToken(tokenMap));
                return ResponseResult.getResponseResult( StatusConstants.STATUS_DEFAULT_YES,
                                                        "登录成功",
                                                        result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.getResponseResult( StatusConstants.STATUS_DEFAULT_NO,
                                        "登录失败");
    }

    @Override
    public ResponseResult insertUserInfo(User user) {
        try {
            userMapper.insertUserInfo(user);
            int maxUserID = userMapper.queryMaxUserID();
            return ResponseResult.getResponseResult( StatusConstants.STATUS_DEFAULT_YES,"注册成功",maxUserID);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseResult.getResponseResult(StatusConstants.STATUS_DEFAULT_NO,"注册失败");
    }

    @Override
    public ResponseResult updateUserInfo(User user,String oldPassword) {
        try {
            if(oldPassword != null) {
                User result = userMapper.queryUserByID(user.getId());
                if (result.getUserpass().equals(oldPassword) == false) {
                    return ResponseResult.getResponseResult(StatusConstants.STATUS_DEFAULT_NO, "密码错误");
                }
            }else{
                user.setUserpass(null);
            }
            userMapper.updateUserInfo(user);
            User resultUser = userMapper.queryUserByID(user.getId());
            return ResponseResult.getResponseResult(StatusConstants.STATUS_DEFAULT_YES,
                                                    "修改成功",
                                                            resultUser);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseResult.getResponseResult(StatusConstants.STATUS_DEFAULT_NO,"修改失败");
    }

    @Override
    public ResponseResult uploadImage(MultipartFile file,User user) {
        if (file.isEmpty()){
            return ResponseResult.getResponseResult(StatusConstants.STATUS_DEFAULT_NO,"文件为空");
        }

        //获取文件名
        String filename = file.getOriginalFilename();
        //获取后缀名
        String suffixName = filename.substring(filename.lastIndexOf(".")+1);
        //获取日期格式类
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        File dir = new File(
"/var/www/html/tib/"+user.getId()+"/"+simpleDateFormat.format(new Date()));
        if(dir.exists()==false){
            try {
                dir.mkdirs();
            } catch (Exception e) {
                return ResponseResult.getResponseResult(StatusConstants.STATUS_DEFAULT_NO,"服务器内部创建文件夹失败");
            }
        }

        //获取本地路径
        String fileLocalPath = dir+"/"+System.currentTimeMillis()+"."+suffixName;

        try {
            file.transferTo(new File(fileLocalPath));
        } catch (IOException e) {
            return ResponseResult.getResponseResult(StatusConstants.STATUS_DEFAULT_NO,"文件转移失败");
        }

        userMapper.uploadImage(user.getId(),fileLocalPath);

        return ResponseResult.getResponseResult(StatusConstants.STATUS_DEFAULT_YES,"文件上传成功");
    }

    @Override
    public PageResult queryPage(User user, int page, int row) {
        List<User> data = userMapper.queryPage(user, (page-1)*row, row);
        long total = data.size();
        long totalPage = total%row == 0 ? total/row : total/row+1;
        PageResult result = new PageResult(total, totalPage, data);
        return result;
    }

    @Override
    public List<Map> select(Map map) {
        List<Map> resMap = new ArrayList<>();
        Integer pageNo = map.containsKey("pageNo")?JSONObject.parseObject(JSON.toJSONString(map.get("pageNo")),Integer.class): 1;
        Integer pageSize = map.containsKey("pageSize")?JSONObject.parseObject(JSON.toJSONString(map.get("pageSize")),Integer.class): 10;
        map.put("pageNo",(pageNo-1)*pageSize);
        map.put("pageSize",pageSize);
        int total = userMapper.selectCount(map);
        List<Map> temp = userMapper.select(map);
        for (Map flag:temp){
            flag.put("total",total);
        }
        resMap.addAll(temp);
        return resMap;
    }

    @Override
    public int update(Map map) {
        return userMapper.update(map);
    }
}
